package dk.itu.samd.group2.tagapastry.util;

import java.io.*;
import java.util.ArrayList;
import java.util.Random;

public class URLGenerator {
	
	private static final int MIN_DATA = 10000,
		MED_DATA = MIN_DATA * 100,
		BIG_DATA = MED_DATA * 10,
		TINY_DATA = 100; 
	
	//private static boolean[] dataExists = {false,false,false};
	private static boolean[] dataExists = {true,true,true,false};
	
	private static void genUrls(int num, String filename) {
		if(num < 1)
			return;
				
		java.io.FileWriter fw = null;
		try {
			fw = new FileWriter(filename);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		BufferedWriter bw = new BufferedWriter(fw);
		
		StringBuffer buf = new StringBuffer();
		Random r = new Random();
		try {
			do {
				int lengthOfUrl = r.nextInt(20);
				if(lengthOfUrl <= 4)
					lengthOfUrl += 4;
				
				for(int i=0; i < lengthOfUrl; i++) {
					
					if(i == lengthOfUrl-4) {
						buf.append(".");
					}
					else {
						buf.append((char)(97 + r.nextInt(25)));
					}
				}
				
				
				bw.write(buf.toString(), 0, buf.length());
				bw.newLine();
				bw.flush();
				buf.delete(0, buf.length()-1);
				
				num--;
			}while(num > 0);
			
			bw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void genTiny() {
		if(dataExists[3])
			return;
		
		URLGenerator.genUrls(TINY_DATA, "tiny.txt");
		dataExists[3] = true;
	}
	
	public static void genMin() {
		if(dataExists[0])
			return;
		
		URLGenerator.genUrls(MIN_DATA,"min.txt");
		dataExists[0] = true;
	}
	
	public static void genMedium() {
		if(dataExists[1])
			return;
		
		URLGenerator.genUrls(MED_DATA,"med.txt");
		dataExists[1] = true;
	}
	
	public static void genBig() {
		if(dataExists[2])
			return;
		
		URLGenerator.genUrls(BIG_DATA,"big.txt");
		dataExists[2] = true;
	}
	
	public static void fullSetPlease() {
		long start = System.currentTimeMillis();
		genTiny();
		genMin();
		genMedium();
		genBig();
		long stop = System.currentTimeMillis() - start;
		System.out.println("I'm done..." + (float)stop/1000 + "seconds");
	}
	
	public static ArrayList<String> readSet(int set1){
		String fileName = set1 == 1 ? "min.txt" : (set1 == 2 ? "med.txt" : (set1 == 3 ? "big.txt" : "tiny.txt"));
		//genTiny();
		try {
			FileReader fr = new FileReader(fileName);
			BufferedReader br = new BufferedReader(fr);
			String line;
			ArrayList<String> data = new ArrayList<String>();
			while(true) {
				line = br.readLine();
				if(line == null || line.length() == 0)
					return data;
					
				data.add(line);
			}
		}
		catch(IOException io) {
			io.printStackTrace();
			return null;
		}
	}
}
